<?php
// E:\qh\cygwin64_php_mini\bin\php.exe E:\qh\speed\mics.php app=ucenter port=8888
error_reporting(0);

use Swoole\Http\Response as Rep;
use Swoole\Http\Request as Req;
use Swoole\Http\Server;

define('APP_DIR', realpath('./'));
define('APP_EVN', 'swoole');
$args = parseArgv();
define('APP_CODE', $args['app']);
define('APP_PORT', $args['port']);
$run = new swoole();
$run->setting(array(
    'enable_static_handler' => true,
    'worker_num' => 2,    //开启两个worker进程
    'max_connection' => 256,
    'dispatch_mode' => 3,
    'package_max_length' => 20 * 1024 * 1024,
    'buffer_output_size' => 20 * 1024 * 1024,
    'document_root' => APP_DIR
));
$run->setPort(APP_PORT);
$run->start();

/**
 * swoole启动
 *
 * Class swoole
 */
class swoole
{
    /** @var Server $http */
    public $http;
    public $queue;
    public $globals;
    public $port = 9999;
    public $setting = array();

    /**
     * 配置
     * @param $setting
     */
    public function setting($setting)
    {
        $this->setting = $setting;
    }

    /**
     * 配置
     * @param $port
     */
    public function setPort($port)
    {
        $this->port = $port;
    }

    /**
     * 启动
     */
    function start()
    {
        echo "
     _______   ______   ___   ___    .______     ______     ______   .___________.
    |   ____| /  __  \  \  \ /  /    |   _  \   /  __  \   /  __  \  |           |
    |  |__   |  |  |  |  \  V  /     |  |_)  | |  |  |  | |  |  |  | `---|  |----`
    |   __|  |  |  |  |   >   <      |   _  <  |  |  |  | |  |  |  |     |  |     
    |  |     |  `--'  |  /  .  \     |  |_)  | |  `--'  | |  `--'  |     |  |     
    |__|      \______/  /__/ \__\    |______/   \______/   \______/      |__|    
                                                                               
                :: Fox Boot V1.1 ::        (swoole:" . swoole_version() . ")\n";
        echo "open web http://foxboot.v.cnbbx.com:{$this->port}/" . APP_CODE . "/\n";
        $this->http = new Server("0.0.0.0", $this->port);
        $this->http->set($this->setting);
        $this->http->on('workerStart', array($this, 'onWorkerStart'));
        $this->http->on('request', array($this, 'onRequest'));
        $this->http->start();
    }

    /**
     * @param $server
     * @param $worker_id
     */
    function onWorkerStart($server, $worker_id)
    {
        global $GLOBALS;
        require(APP_DIR . '/lib/core.php');
        logs("onWorkerStart workerId : [{$worker_id}]");
        if ($this->globals == null) {
            $this->globals = true;
            $_SERVER["HTTP_HOST"] = "app.v.cnbbx.com";
            $GLOBALS += require(APP_DIR . '/config.php');
        }
    }

    /**
     * @param Req $request
     * @param Rep $response
     * @return mixed|void
     */
    function onRequest($request, $response)
    {
        global $GLOBALS, $app;
        $app = new Core();
        $app->response = $response;
        $ret = [];
        $ret += !$request->get ? [] : $request->get;
        $ret += !$request->post ? [] : $request->post;
        $app->request = $ret;
        $app->server = $request->server;
        $app->header = $response;
        $response->header("Server", "FoxBoot/v1.1");
        $response->header("Access-Control-Allow-Origin", '*');
        $response->header("Content-Type", "text/html; charset=utf-8");
        if ($request->server['request_uri'] == '/favicon.ico' || $request->server['path_info'] == '/favicon.ico') {
            return $response->end();
        }
        $GLOBALS['out_handler'] = function ($html) use ($response) {
            $response->write($html);
            return $response->end();
        };
        // 启动一个服务
        $arr = explode('/', $app->server['request_uri']);
        $app->app_module = APP_CODE;
        $app->app_controller = !empty($arr[2]) ? strtolower($arr[2]) : 'main';
        $app->app_action = !empty($arr[3]) ? strtolower($arr[3]) : 'index';
        $controller_name = str_replace("/", "\\", str_replace("//", "/", str_replace("\\\\", "\\", "app" . DS . $app->app_module . DS . 'controller' . DS . $app->app_controller . 'Control')));
        if (!empty($app->app_module)) if (!is_available_className($app->app_module)) return err("Err: Module '$app->app_module' is not correct!");
        if (!is_available_className($app->app_controller)) return err("Err: Controller '$controller_name' is not correct!");
        if (!class_exists($controller_name, true)) return err("Err: Controller '$controller_name' is not exists!");
        if (!method_exists($controller_name, $app->app_action)) return err("Err: Method '$app->app_action' of '$controller_name' is not exists!");
        $controller_obj = new $controller_name($app);
        $arr = explode('/', $app->server['request_uri']);
        try {
            call_user_func_array(array($controller_obj, $app->app_action), count($arr) > 4 ? array_slice($arr, 4) : array());
        } catch (Exception $e) {
            return $response->end();
        }
        if ($controller_obj->_auto_display) {
            $auto_tpl_name = (empty($app->app_module) ? '' : $app->app_module . DS) . $app->app_controller . '_' . $app->app_action . '.html';
            if (file_exists(APP_DIR . DS . 'app' . DS . 'view' . DS . $auto_tpl_name)) $controller_obj->display($auto_tpl_name);
        }
        return $response->end();
    }
}

/**
 * 系统参数
 *
 * @return array
 */
function parseArgv()
{
    $ret = array();
    $str = implode('&', $GLOBALS['argv']);
    $arr1 = explode('&', $str);
    foreach ($arr1 as $line) {
        $arr2 = explode('=', $line);
        if (count($arr2) != 2) continue;
        $ret[$arr2[0]] = urldecode($arr2[1]);
    }
    if (!isset($ret['app']) || !isset($ret['port'])) {
        echo('必须指定参数:app,port');
        exit();
    }
    return $ret;
}
